<?

/*
**		SOCIAL : YouTube
**		
**		references: 
		http://code.google.com/apis/youtube/2.0/reference.html#YouTube_elements_reference
		http://code.google.com/apis/youtube/2.0/developers_guide_protocol_api_query_parameters.html
		http://code.google.com/apis/youtube/2.0/developers_guide_jsonc.html
		http://code.google.com/apis/youtube/articles/view_youtube_jsonc_responses.html
		
**		sample feedUrl: http://gdata.youtube.com/feeds/api/videos?v2&alt=jsonc&q=Norah+Jones&orderby=viewCount&max-results=10
*/


class YOUTUBE extends SOCIAL {
	
	function __construct() { }
	
	public function request( $searchVars, $category, $maxResults = 5, $startIndex = 1, $orderBy = "viewCount" ) {

		$this->searchVars	= $searchVars;
		$this->category		= $category;
		$this->maxResults	= $maxResults;
		$this->startIndex	= $startIndex;
		$this->orderBy		= $orderBy;
		
		// BUILD REQUEST
		$this->json = $this->get_json( $this->get_feed_url() );
	}
	
	// query vars
	var $feedUrlBase = 'http://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc';
	var $safeSearch = 'strict';
	
	// response strings
	var $json;
	
	public function get( $arg = 'id' ) {
		
		if( !is_array( $arg )) $arg = func_get_args();

		if( count( $arg ) == 1 ) return $this->get_item_data( $arg );
		else {
			foreach( $arg as $value )
				$array[ $value ] = $this->get_item_data( $value );
			return $array;
		};
	}
	
	public function filter( $arg = 'id' ) {
	
		for( $n=0; $n < count( $this->json->items ); $n++ ) {			
			
			$nodes[] = $this->get( func_get_args() );
			next( $this->json->items );
		}
		return $nodes;
	}
	
	private function get_feed_url() {
	
		$searchQuery = (is_array($this->searchVars)) ? implode(" ", $this->searchVars) : $this->searchVars;
		
		return ( $this->feedUrlBase . 
		'&safesearch='. $this->safeSearch . 
		'&category='. urlencode(trim($this->category)) . 
		'&q='. urlencode(trim($searchQuery)) . 
		'&orderby='. $this->orderBy . 
		'&max-results='. $this->maxResults . 
		'&start-index='. $this->startIndex );
	}
	
	private function get_json ( $feed ) {
		$json = file($feed);
		return json_decode( $json[0] )->data;
	}
	
	// options: id, uploader, category, title, description, tags, duration, rating, ratingCount, viewCount, favoriteCount, commentCount, 
	// thumbnail, player, embedAllowed
	private function get_item_data ( $type = 'id' ) {

		$node = current( $this->json->items );
		
		switch( $type ) {
			case 'thumbnail': return $node->$type->sqDefault; break;
			case 'player': return $node->$type->default; break;
			case 'embedAllowed': return $node->accessControl->embed; break;
			default: return $node->$type;
		}
	}
	
}


?>